package com.yu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yu.model.entity.User;
import com.yu.model.pojo.Result;
import com.yu.service.UserService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/student")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 普通用户登录 （学生）
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request){

        //对密码进行md5加密
        String userPassword = user.getUserPassword();
        String password = DigestUtils.md5DigestAsHex(userPassword.getBytes());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> eq = queryWrapper.eq(User::getUserAccount, user.getUserAccount());
        User one = userService.getOne(eq);
        if(one == null){
            return Result.error("账户或者密码错误");
        }
        if(!one.getUserPassword().equals(password)){
            return Result.error("账户或者密码错误");
        }
        request.getSession().setAttribute("student",one.getId());
        return Result.success(one);
    }


    /**
     * 学生退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().removeAttribute("student");
        return Result.success("退出成功");
    }




}
